﻿using System;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using SJKP.PDFConversion.Client;
using SJKP.PDFConversion.Extensions;

namespace SJKP.PDFConversion.Layouts.SJKP.PDFConversion
{
    public partial class PdfProcessItem : LayoutsPageBase
    {
        protected override void OnLoad(EventArgs e)
        {
            DialogMaster master = Page.Master as DialogMaster;
            if (master != null)
            {
                master.OkButton.Enabled = true;
            }
            base.OnLoad(e);
        }

        protected override void OnInit(EventArgs e)
        {
            DialogMaster master = Page.Master as DialogMaster;
            if (master != null)
            {
                master.OkButton.Click += new EventHandler(OkButton_Click);
            }

            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string listIdStr = Request.QueryString["ListID"];
            string itemIdStr = Request.QueryString["ItemID"];
            if (string.IsNullOrEmpty(itemIdStr) || string.IsNullOrEmpty(listIdStr))
            {
                lblInformation.Text = "Query string parameters not specified";
                return;
            }
            Guid listId = new Guid(listIdStr);
            int itemId = 0;
            if (!Int32.TryParse(itemIdStr, out itemId))
            {
                lblInformation.Text = "ItemId was not a valid id";
                return;
            }
            SPWeb web = SPContext.Current.Web;
            SPDocumentLibrary list = null;
            try
            {
                list = web.Lists[listId] as SPDocumentLibrary;
            }
            catch (Exception ex)
            {
                // Log
                return;
            }
            if (list == null)
                return;
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                web.AllowUnsafeUpdates = true;
                operation.Begin();
                SPListItem item = list.GetItemById(itemId);
                string newFilename = String.Concat(Path.GetFileNameWithoutExtension(item.File.Name), "_converted",
                                                   Path.GetExtension(item.File.Name));

                byte[] converted = new OCRClientHelper(SPServiceContext.Current).ProcessPdf(item.File.OpenBinary());
                list.UploadFile(converted, newFilename);
                SendResponseForPopUI();
            }
        }

        protected void OkButton_Click(object sender, EventArgs e)
        {
            SendResponseForPopUI();
        }
    }
}
